<?php

class Jijaf_Auth_Controller extends Base_Controller 
{

    public function action_profile() {
        return View::make('jijaf.auth.profile');
    }

    public function action_login() {
        return View::make('jijaf.auth.login');
    }

    public function action_handle_profile() {
        $input = Input::all();

        $rules = array(
            'old_password' => 'required|currentpassword',
            'password' => 'required|between:5,64|confirmed|different:old_password',
        );

        $validation = Validator::make($input, $rules);

        if ($validation->fails()) {
            return Redirect::to_action('jijaf.auth@profile')
                                ->with_errors($validation);
        }

        Auth::user()->set_password(Input::get('password'));
        Auth::user()->save();

        return Redirect::to_action('jijaf.auth@profile')
                             ->with('success',
                                    'Password updated successfully.');
    }
    public function action_handle_login() {
        $userdata = array(
            'username' => Input::get('username'),
            'password' => Input::get('password')
        );

        if (Auth::attempt($userdata)) {
            // If user attempted to access specific URL before logging in
            if (Session::has('pre_login_url')) {
                $url = Session::get('pre_login_url');
                Session::forget('pre_login_url');
                return Redirect::to($url);
            }
            else {
                return Redirect::to('/');
            }
        }
        else {
            return Redirect::to_action('jijaf.auth@login')
                ->with('login_errors', true);
        }
    }

    public function action_logout() {
        Auth::logout();
        return Redirect::to('/');
    }
}
